//
//  KKDatePicker.m
//  SHDoctor
//
//  Created by Mac mini on 15/10/12.
//  Copyright © 2015年 ShiHeng. All rights reserved.
//

#import "KKDatePicker.h"

#import <objc/runtime.h>

static NSString *KKDatePickerDisappearAnimationName = @"KKDatePickerDisappearAnimationName";

@interface UIViewController(KKDatePicker)

@end

@implementation UIViewController(KKDatePicker)

+ (void)load {
    
    Method viewDidDisappear = class_getInstanceMethod([self class], NSSelectorFromString(@"viewWillDisappear:"));
    Method kk_viewDidDisappear = class_getInstanceMethod([self class], @selector(kk_viewWillDisappear:));
    method_exchangeImplementations(viewDidDisappear, kk_viewDidDisappear);
}

- (void)kk_viewWillDisappear:(BOOL)animated {
    
    [[NSNotificationCenter defaultCenter] postNotificationName: KKDatePickerDisappearAnimationName object: self];
    
    [self kk_viewWillDisappear: animated];
}

@end


@interface KKDatePicker() {
    
    BOOL _isShow;
    UILabel *_titleLabel;
}

@end

@implementation KKDatePicker

#pragma mark - Public methods

- (instancetype)initWithPickerMode:(UIDatePickerMode )pickerMode {
    
    CGFloat width = CGRectGetWidth([[UIScreen mainScreen] bounds]);
    CGFloat height = CGRectGetHeight([[UIScreen mainScreen] bounds]);
    
    self = [super initWithFrame: CGRectMake(0, height, width, 260)];
    if (self) {
        
        self.backgroundColor = [UIColor whiteColor];
        self.windowLevel = UIWindowLevelAlert + 1;
        
        _picker = [[UIDatePicker alloc] initWithFrame: CGRectMake(0, 44, width, 216)];
        _picker.datePickerMode = pickerMode;
        [self addSubview: _picker];
        
        {
            UIToolbar *toolBar = [[UIToolbar alloc] initWithFrame: CGRectMake(0, 0, width, 44)];
            {
                UIBarButtonItem *leftSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem: UIBarButtonSystemItemFixedSpace target: nil action: nil];
                leftSpace.width = 10;
                UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem: UIBarButtonSystemItemCancel target: self action: @selector(actionOfCancel:)];
                
                UIBarButtonItem *spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem: UIBarButtonSystemItemFlexibleSpace target: nil action: nil];
                
                UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem: UIBarButtonSystemItemSave target: self action: @selector(actionOfSure:)];
                UIBarButtonItem *rightSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem: UIBarButtonSystemItemFixedSpace target: nil action: nil];
                rightSpace.width = 10;
                
                [toolBar setItems: @[leftSpace, leftItem, spaceItem, rightItem, rightSpace]];
                
                _titleLabel = [[UILabel alloc] initWithFrame: CGRectMake(80, 12, width - 160, 20)];
                _titleLabel.backgroundColor = [UIColor clearColor];
                _titleLabel.font = [UIFont systemFontOfSize: 16];
                _titleLabel.textAlignment = NSTextAlignmentCenter;
                _titleLabel.textColor = [UIColor darkGrayColor];
                [toolBar addSubview: _titleLabel];
            }
            [self addSubview: toolBar];
        }
        self.hidden = true;
//        [self makeKeyAndVisible];
        
        [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(listenDatePickerState:) name: KKDatePickerDisappearAnimationName object: nil];
    }
    return self;
}

- (void)dealloc {
    
    [[NSNotificationCenter defaultCenter] removeObserver: self];
}

- (void)show {
    
    [self showWithTitle: nil];
}

- (void)showWithTitle:(NSString*)title {
    
    if (_isShow) {
        return;
    }
    
    _titleLabel.text = title;
    _isShow = true;
    
    self.hidden = false;
    __weak typeof(self) weakself = self;
    
    [self makeKeyAndVisible];
    
    CGFloat height = CGRectGetHeight([[UIScreen mainScreen] bounds]);
    CGFloat width = CGRectGetWidth([[UIScreen mainScreen] bounds]);
    CGFloat selfHeight = CGRectGetHeight(self.bounds);
    
    [[UIApplication sharedApplication] beginIgnoringInteractionEvents];
    [UIView animateWithDuration: 0.25 animations:^{
        weakself.center = CGPointMake(width/2, height - selfHeight/2);
    } completion:^(BOOL finished) {
        
        [[UIApplication sharedApplication] endIgnoringInteractionEvents];
    }];
}


- (void)cancel {
    
    if (!_isShow) {
        return;
    }
    __weak typeof(self) weakself = self;
    
    CGFloat height = CGRectGetHeight([[UIScreen mainScreen] bounds]);
    CGFloat width = CGRectGetWidth([[UIScreen mainScreen] bounds]);
    CGFloat selfHeight = CGRectGetHeight(self.bounds);
    
    [[UIApplication sharedApplication] beginIgnoringInteractionEvents];
    [UIView animateWithDuration: 0.25 animations:^{
        weakself.center = CGPointMake(width/2, height + selfHeight/2);
    } completion:^(BOOL finished) {
        
        [[UIApplication sharedApplication] endIgnoringInteractionEvents];
        weakself.hidden = true;
        _isShow = false;
        
        [weakself resignKeyWindow];
    }];
}

#pragma mark - Action methods

- (void)actionOfCancel:(UIBarButtonItem *)item {
    
    [self cancel];
    
    if (_cancleBlock) {
        _cancleBlock();
    }
}

- (void)actionOfSure:(UIBarButtonItem *)item {
    
    [self cancel];
    
    if (_saveBlock) {
        _saveBlock([_picker date]);
    }
}

#pragma mark - NSNotification methods

- (void)listenDatePickerState:(NSNotification *)notification {
    
    id object = notification.object;
    
    if (object &&[object isKindOfClass: [UIViewController class]]) {
        [self cancel];
    }
}

@end
